package com.summer.data.connection.sessioninterface;

import com.summer.data.Jsql;
import com.summer.data.dialect.Dialect;
import com.summer.data.jql.behavior.FilterAble;
import com.summer.data.rs.extractor.KeysExtractor;
import com.summer.data.table.BaseTable;

import java.util.List;

/**
 * @author 345480567@qq.com
 */
public interface PersistenceSessionInterface extends JsqlSessionInterface {

    default Integer insert(Object t) {
        return insert(t, false);
    }

    default Integer insert(Object t, Boolean returnId) {
        Dialect dialect = getDialect();
        Jsql jsql = dialect.buildInsertSql(t);
        if (returnId) {
            if (t instanceof BaseTable) {
                BaseTable bt = (BaseTable) t;
                KeysExtractor tableKeysExtractor = dialect.buildKeysExtractor(bt);
                return executeUpdate(jsql, tableKeysExtractor);
            }
        }
        return executeUpdate(jsql);
    }

//    default Integer update(BaseTable tableInstance) {
//        return updateBy(tableInstance);
//    }

    default <T extends BaseTable> Integer update(T t, FilterAble... filters) {
        Dialect dialect = getDialect();
        Jsql jsql = dialect.buildUpdateSql(t, filters);
        return executeUpdate(jsql);
    }

//    default <T extends BaseTable> Integer upsert(T t, FilterAble... filters) {
//        Dialect dialect = getDialect();
//        if (dialect.isSupportUpsert()) {
//            Jsql jsql = dialect.buildUpsertSql(t, filters);
//            return executeUpdate(jsql);
//        } else {
//            Jsql queryJsql = dialect.buildSelectSql(t.getClass(), filters);
//            Integer count = count(queryJsql);
//            if (count > 0) {
//                Jsql jsql = dialect.buildUpdateSql(t, filters);
//                return executeUpdate(jsql);
//            } else {
//                Jsql jsql = dialect.buildInsertSql(t);
//                return executeUpdate(jsql);
//            }
//        }
//    }

//    default Integer delete(Class<? extends BaseTable> clazz) {
//        return deleteBy(clazz);
//    }

    default Integer delete(Class<? extends BaseTable> clazz, FilterAble... filters) {
        Dialect dialect = getDialect();
        Jsql jsql = dialect.buildDeleteSql(clazz, filters);
        return executeUpdate(jsql);
    }

    default <T extends BaseTable> Integer delete(T t, FilterAble... filters) {
        return delete(t.getClass(), filters);
    }

}
